package com.cs307.redcross.client;

import java.io.Serializable;
import java.security.MessageDigest;
import java.util.Vector;
//import javax.mail.internet.InternetAddress;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;

public class RegisterUserContent extends DialogBox implements Serializable {

	private static final long serialVersionUID = 4468006641815672683L;
	private DatabaseHandlerServiceAsync databaseHandlerService = (DatabaseHandlerServiceAsync) GWT.create(DatabaseHandlerService.class);	

    private final String COL_WIDTH = "150px";
	
	private TextBox firstName;
	private TextBox lastName;
	private TextBox email;
	private TextBox phoneNumber;
	private ListBox carrier;
	private PasswordTextBox newPass;
	private PasswordTextBox retypeNewPass;
	private Button Create;
	
	@SuppressWarnings("unused")
	private Vector<Person> personVector;
	
	public RegisterUserContent() {	
		this.setText("Sign Up");

		final AbsolutePanel absolutePanel = new AbsolutePanel();
		setWidget(absolutePanel);
		absolutePanel.setSize("248px", "427px");

		firstName = new TextBox();
		lastName = new TextBox();
		email = new TextBox();
		phoneNumber = new TextBox();
		phoneNumber.setMaxLength(10);
		carrier = new ListBox();
		carrier.addItem("AT&T");
		carrier.addItem("Verizon");
		carrier.addItem("T-Mobile");
		carrier.addItem("Virgin Mobile");
		carrier.addItem("Nextel");
		carrier.addItem("Boost");
		carrier.addItem("Alltel");
		newPass = new PasswordTextBox();
		retypeNewPass = new PasswordTextBox();
		Create = new Button("Create New Account");

		//create firstname textbox
		Label label = new Label("First Name");
		label.setStyleName("h1");
		absolutePanel.add(label, 10, 10);
		absolutePanel.add(firstName, 10, 28);
		firstName.setWidth("150px");
		
		//create lastname textbox
		Label label_6 = new Label("Last Name");
		label_6.setStyleName("h1");
		absolutePanel.add(label_6, 10, 59);
		absolutePanel.add(lastName, 10, 77);
		lastName.setWidth("150px");
		
		//create email textbox
		Label label_5 = new Label("Email");
		label_5.setStyleName("h1");
		absolutePanel.add(label_5, 10, 108);
		absolutePanel.add(email, 10, 132);
		email.setWidth("150px");
		
		//create cellphone textbox
		Label label_4 = new Label("Cell Phone");
		label_4.setStyleName("h1");
		absolutePanel.add(label_4, 11, 163);
		absolutePanel.add(phoneNumber, 10, 187);
		phoneNumber.setWidth("150px");
		
		//create carrier listbox
		Label label_3 = new Label("Carrier");
		label_3.setStyleName("h1");
		absolutePanel.add(label_3, 10, 218);
		absolutePanel.add(carrier, 11, 242);
		carrier.setWidth("157px");
		
		//create password textbox
		Label label_2 = new Label("Password");
		label_2.setStyleName("h1");
		absolutePanel.add(label_2, 10, 270);
		absolutePanel.add(newPass, 10, 294);
		newPass.setWidth(COL_WIDTH);
		
		//create retype newpassword textbox
		Label label_1 = new Label("Retype Password");
		label_1.setStyleName("h1");
		absolutePanel.add(label_1, 10, 325);
		absolutePanel.add(retypeNewPass, 10, 349);
		retypeNewPass.setWidth(COL_WIDTH);
		
		//create updateInfo button
		absolutePanel.add(Create, 10, 380);
		
		// Listen for mouse events on the updateInfo button
		Create.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event){
				try {
					if(newPass.getValue().equals(retypeNewPass.getValue())) {
						if (!phoneNumber.getValue().equals(null)) {
							if (ValidateEmail(email.getValue())) {
								if (ValidatePhoneNumber(phoneNumber.getValue())) {
		//							if (duplicateEmail(email.getValue())) {
									databaseHandlerService.getPerson(email.getValue(), new AsyncCallback<Person>() {
		
										@Override
										public void onFailure(Throwable caught) {
											// TODO Auto-generated method stub
											Window.alert("Failed");
										}
		
										@Override
										public void onSuccess(Person result) {
											// TODO Auto-generated method stub
											try {
												if (result == null)
													createInfo();
												else {
													Window.alert("This email account " + email.getValue() + " is using. Please write different email");
													email.setValue(null);
												}
											} catch (Exception e) {
												// TODO Auto-generated catch block
												e.printStackTrace();
											}
										}
									});
		//							} else {
		//								Window.alert("This email account " + email.getValue() + " is using. Please write different email");
		//								email.setValue(null);
		//							}
				        		} else {
				        			Window.alert("Invalid Phonenumber. Please type numbers only");
				        			phoneNumber.setValue(null);
				        		}
			        		} else {
			        			Window.alert("Invalid Eamil format. Please type into right format");
			        			email.setValue(null);
			        		}
						} else {
							databaseHandlerService.getPerson(email.getValue(), new AsyncCallback<Person>() {
								
								@Override
								public void onFailure(Throwable caught) {
									// TODO Auto-generated method stub
									Window.alert("Failed");
								}

								@Override
								public void onSuccess(Person result) {
									// TODO Auto-generated method stub
									try {
										if (result == null)
											createInfo();
										else {
											Window.alert("This email account " + email.getValue() + " is using. Please write different email");
											email.setValue(null);
										}
									} catch (Exception e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
								}
							});
						}
		        	} else {
		        		Window.confirm("Password not matched. please retype the password!");
			        	newPass.setValue(null);
			        	retypeNewPass.setValue(null);
		        	}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		  });
		  
		 // Listen for keyboard events in the input box.
		Create.addKeyPressHandler(new KeyPressHandler() {
		    public void onKeyPress(KeyPressEvent event) {
		      if (event.getCharCode() == KeyCodes.KEY_ENTER) {
		        try {
		        	if(newPass.getValue().equals(retypeNewPass.getValue())) {
						if (ValidatePhoneNumber(phoneNumber.getValue())) {
//							if (duplicateEmail(email.getValue())) {
							databaseHandlerService.getPerson(email.getValue(), new AsyncCallback<Person>() {

								@Override
								public void onFailure(Throwable caught) {
									// TODO Auto-generated method stub
									Window.alert("Failed");
								}

								@Override
								public void onSuccess(Person result) {
									// TODO Auto-generated method stub
									try {
										if (result == null)
											createInfo();
										else {
											Window.alert("This email account " + email.getValue() + " is using. Please write different email");
											email.setValue(null);
										}
									} catch (Exception e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
								}
							});
//							} else {
//								Window.alert("This email account " + email.getValue() + " is using. Please write different email");
//								email.setValue(null);
//							}
		        		} else {
		        			Window.alert("Invalid Phonenumber. Please type numbers only");
		        			phoneNumber.setValue(null);
		        		}
		        	} else {
		        		Window.confirm("Password not matched. please retype the password!");
			        	newPass.setValue(null);
			        	retypeNewPass.setValue(null);
		        	}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		      }
		    }
		  });

		// Move cursor focus to the name text box.
		firstName.setFocus(true);	
		
		Button btnCancel = new Button("Cancel");
		btnCancel.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				hide();
			}
		});
		absolutePanel.add(btnCancel, 156, 380);
		btnCancel.setSize("73px", "24px");
		
		Label lbltypeDigts = new Label("(Type 10 digts only)");
		absolutePanel.add(lbltypeDigts, 79, 163);

		databaseHandlerService.getAllPeople(new AsyncCallback<Vector<Person>>(){
			public void onFailure(Throwable caught) {
				Window.alert("Failed to get volunteers list");
			}

			public void onSuccess(Vector<Person> result) {
				try {
					personVector = result;
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		
	}
	
	
	private void createInfo() throws Exception {
	
		databaseHandlerService.startDatabaseHandler( new AsyncCallback<Void>() {
			
			public void onFailure(Throwable caught) {
				Window.alert("Startup failed.");
			}

			public void onSuccess(Void result) {
				try {
					//Window.alert("Startup Sucedded");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		String fName = firstName.getValue();
		String lName = lastName.getValue();
		String e = email.getValue();
		String car = carrier.getItemText(carrier.getSelectedIndex());
		String cell = phoneNumber.getValue();
		String pass = newPass.getValue();
		Volunteer vol = null;
		if (cell == null){
			vol = new Volunteer(fName, lName, e, "", "", "", e, pass, null);
		} else {
			if (ValidatePhoneNumber(cell))
				vol = new Volunteer(fName, lName, e, car, cell, car, e, pass, null);
			else {
				Window.alert("Invalid Phonenumber!");
				phoneNumber.setText("");
			}
		}
		databaseHandlerService.sendConfirmation(vol, new AsyncCallback<Void>() {
					
			public void onFailure(Throwable caught) {
				Window.alert("Failed Update Info");
			}
	
			public void onSuccess(Void result) {
				try {
					Window.confirm("Success!!!!!");
					hide();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	}
	@SuppressWarnings("unused")
	private String Encripted(String password)
    {
            String algorithm = "SHA";
            byte[] plainText = password.getBytes();

            MessageDigest md = null;
            try {
                md = MessageDigest.getInstance(algorithm);
            } catch (Exception e) {
                e.printStackTrace();
            }

            md.reset();
            md.update(plainText);
            byte[] encodedPassword = md.digest();

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < encodedPassword.length; i++) {
                if ((encodedPassword[i] & 0xff) < 0x10) {
                    sb.append("0");
                }

                sb.append(Long.toString(encodedPassword[i] & 0xff, 16));
            }
        return sb.toString() ;
    } 
	
	private static boolean ValidatePhoneNumber(String phNumber)
    {
            boolean valResult = false;
            String numPattern = "(\\d)?(\\d{3})?\\d{3}\\d{4}";
            valResult = phNumber.matches(numPattern);

            return valResult;
    }
	
	public static boolean ValidateEmail(String email)
    {
            boolean valResult = false;
            String numPattern =  "^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$";
            valResult = email.matches(numPattern);
            return valResult;
    }
}
